<template>
  <a-col :span="12">
    <a-space mb-4>
      <a-button type="primary" @click="addOption"> 新建选项 </a-button>
      <a-button
        type="primary"
        @click="batchRemove"
        :disabled="!selectedRowKeys.length"
      >
        批量删除
      </a-button>
    </a-space>
    <a-table
      size="small"
      :columns="columns"
      :pagination="false"
      bordered
      :data-source="tableCollection.tableData"
      :scroll="{ y: rowH - 88 }"
      :row-selection="{
        selectedRowKeys,
        onChange: selectChange,
      }"
      :row-key="genRowKey"
      :custom-row="customRow"
    >
      <template #bodyCell="{ column, value, record }">
        <template v-if="column.dataIndex == 'option_name'">
          <a-input
            v-if="record.isEdit"
            ref="inputRef"
            @blur="saveOption"
            v-model:value.trim="tempValue"
            placeholder="请输入"
            @press-enter="inputRef?.blur()"
            :maxlength="20"
          ></a-input>
          <div v-else>
            <a-popover>
              <template #content>
                <img :src="record.image_url" :style="{ maxHeight: '200px' }" />
              </template>
              <img
                v-if="!!record.image_url"
                class="option-image"
                :src="record.image_url"
              />
            </a-popover>
            {{ record.alias_name || record.option_name }}
            <a-button
              type="link"
              :icon="h(PictureOutlined)"
              @click="openPicModal(record as Row)"
            ></a-button>
            <a-button
              type="link"
              :icon="h(EditOutlined)"
              @click="modify(record.alias_name)"
            ></a-button>
          </div>
        </template>
        <template v-if="column.dataIndex == 'options'">
          <a-tag
            v-for="item in (value as WebOption[])"
            :key="item.option_value"
            closable
            @close.prevent="tableCollection.removeOption(record as Row, item)"
          >
            {{ item.option_name }}
          </a-tag>
        </template>

        <template v-if="column.dataIndex == 'action'">
          <a-button
            type="link"
            v-if="(record as Match).options.length"
            @click="tableCollection.removeAll(record as Row)"
          >
            清空
          </a-button>
          <a-button
            type="link"
            v-else
            @click="tableCollection.removeRow(record as Row)"
          >
            删除
          </a-button>
        </template>
      </template>
    </a-table>
    <pic-modal ref="picModal" @ok="onPicModalOk" />
  </a-col>
</template>

<script lang="tsx" setup>
import { TableColumnType } from 'ant-design-vue';
import { EditOutlined, PictureOutlined } from '@ant-design/icons-vue';
import OptionTable, { type Row } from './table';
import PicModal from './PicModal.vue';
import type { Match, WebOption } from '../type';
import { Emitter } from 'mitt';

const props = defineProps<{
  tableCollection: OptionTable;
  rowH: number;
  mitt: Emitter<any>;
}>();
const picModal = ref<InstanceType<typeof PicModal>>();
const columns: TableColumnType[] = [
  {
    title: '选项',
    dataIndex: 'option_name',
    customCell: row => {
      return { rowSpan: row.rowSpan };
    },
    width: 200,
  },
  {
    title: '匹配站点条件',
    ellipsis: true,
    customRender({ record }) {
      const { website_code, category_name, condition_name } = record as Row;
      return `${website_code}-${category_name}:${condition_name}`;
    },
    width: 300,
  },
  {
    title: '关联站点条件选项',
    dataIndex: 'options',
    width: 300,
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: '80px',
    fixed: 'right',
  },
];

const inputRef = ref<HTMLInputElement>();
const tempValue = ref('');
const addOption = () => {
  tempValue.value = '';
  props.tableCollection.addOption(inputRef);
};
const saveOption = () => {
  props.tableCollection.save(tempValue.value, inputRef);
  tempValue.value = '';
};

const modify = (option_name: string) => {
  props.tableCollection.modifyOption(option_name, inputRef, tempValue);
};

const openPicModal = (row: Row) => {
  const { conditionMap } = props.tableCollection.getMap;
  const condition = conditionMap.get(row.alias_name);
  if (condition) {
    picModal.value?.openPicModal(condition);
  }
};

const onPicModalOk = (option_name: string, url: string) => {
  props.tableCollection.saveImage(option_name, url);
};
// window._tb = props.tableCollection;

const selectedRowKeys = ref([]);
const selectedRows = ref<Row[]>([]);

const selectChange = (keys, rows) => {
  selectedRowKeys.value = keys;
  selectedRows.value = rows;
};
const batchRemove = () => {
  selectedRows.value.forEach(item => {
    props.tableCollection.removeRow(item);
  });
  selectedRowKeys.value = [];
  selectedRows.value = [];
};
const genRowKey = (item: Row) => {
  const { condition_name, option_name, website_code, category_name } =
    item as Row;
  return condition_name + option_name + website_code + category_name;
};

const activeKey = ref('');
const rowMap = ref<Map<string, WebOption>>(new Map());
const activeRow = computed(() => rowMap.value.get(activeKey.value));
const customRow = (record: Row) => {
  if (
    activeRow.value &&
    record.options.some(item =>
      compare(item, activeRow.value!, [
        'website_code',
        'category_name',
        'condition_name',
        'option_name',
        'option_code',
        'image_url',
      ])
    )
  ) {
    nextTick(() => {
      const el = document.querySelector(
        `tr[data-row-key='${genRowKey(record)}']`
      );
      el?.scrollIntoView({ behavior: 'smooth' });
    });
    return {
      class: 'row-active',
    };
  }
  return {};
};
onMounted(() => {
  props.mitt.on('changeKey', key => {
    activeKey.value = key;
  });
  props.mitt.on('changeRow', value => {
    const { key, row } = value as any;
    if (row) {
      rowMap.value.set(key, row);
    } else {
      rowMap.value.delete(key);
    }
  });
});
</script>

<style lang="scss" scoped>
.option-image {
  margin-right: 8px;
  width: 24px;
  height: 24px;
  vertical-align: middle;
}
</style>
